package com.meow_woof.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meow_woof.dto.Result;
import com.meow_woof.dto.ScrollResult;
import com.meow_woof.dto.UserDTO;
import com.meow_woof.entity.Blog;
import com.meow_woof.entity.Follow;
import com.meow_woof.entity.User;
import com.meow_woof.mapper.BlogMapper;
import com.meow_woof.service.IBlogService;
import com.meow_woof.service.IFollowService;
import com.meow_woof.service.IUserService;
import com.meow_woof.utils.SystemConstants;
import com.meow_woof.utils.UserHolder;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.meow_woof.utils.RedisConstants.FEED_KEY;

/**
 * 服务实现类
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Autowired
    private IUserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IFollowService followService;
    public Result queryHotBlog(Integer current) {
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog->{
            queryBlogUser(blog);
            isLiked(blog);

        });

        return Result.ok(records);
    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    public Result queryById(Long id) {
        Blog blog = getById(id);
        queryBlogUser(blog);
        isLiked(blog);

        return Result.ok(blog);
    }

    private void isLiked(Blog blog) {
        Long userId = UserHolder.getUser().getId();
        String key="blog:liked:"+blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score!=null);
    }

    public Result likeBlog(Long id) {

        Long userId = UserHolder.getUser().getId();
        String key="blog:liked:"+id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if(score==null){
            boolean success = update().setSql("liked=liked+1").eq("id", id).update();
            if(success){
                stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());
            }

        }else{
            boolean success = update().setSql("liked=liked-1").eq("id", id).update();
            if(success){
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
            }


        }

        return Result.ok();
    }

    public Result queryBlogLikes(Long id) {
        List<Long> list = stringRedisTemplate.opsForZSet().range("blog:liked:" + id, 0, 4).stream().map(Long::valueOf).collect(Collectors.toList());
        if(list.isEmpty()){
            return  Result.ok(Collections.emptyList());
        }
        String idStr= StrUtil.join(",",list);
        List<Object> userDTOS = userService.query().in("id", list).last("ORDER BY FIELD(id," + idStr + ")").list()
                .stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOS);
    }

    public Result saveBlog(Blog blog) {
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        boolean save = save(blog);
        if (!save) {
            Result.fail("笔记保存未成功");
        }

        List<Follow> userId = followService.query().eq("follow_user_id", user.getId()).list();
        if(userId==null||userId.isEmpty()){
            return Result.ok("无人关注他");

        }
        for(Follow follow:userId){
            stringRedisTemplate.opsForZSet().add(FEED_KEY+follow.getUserId(),blog.getId().toString(),System.currentTimeMillis());

        }
        return Result.ok(blog.getId());



    }

    public Result queryBlogOfFollow(Long max, Integer offset) {
        Long userId = UserHolder.getUser().getId();
        String key=FEED_KEY+userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate
                .opsForZSet().reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        if(typedTuples==null||typedTuples.isEmpty()){
            return Result.ok();
        }
        List<Long> ids=new ArrayList<>(typedTuples.size());
        int os=1;
        long minTime=0L;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            ids.add(Long.valueOf(typedTuple.getValue()));
            long time = typedTuple.getScore().longValue();
            if(time==minTime){
                os++;
            }else {
                minTime=time;
                os=1;
            }
        }
        String idStr = StringUtil.join(ids, ",");
        List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Blog blog : blogs) {
            queryBlogUser(blog);
            isLiked(blog);

        }
        ScrollResult sr=ScrollResult.builder()
                .minTime(minTime)
                .list(blogs)
                .offset(os)
                .build();
        return Result.ok(sr);
    }
}
